<template>
  <div class="page-container">
    <header class="header">
      <div class="header-content">
        <router-link to="/" class="logo">
          <h1>匿名社交网络系统</h1>
        </router-link>
        <div class="user-info">
          <el-dropdown @command="handleCommand">
            <div class="user-dropdown">
              <el-avatar :size="32" :src="userStore.userInfo?.avatar">
                {{ userStore.userInfo?.nickname?.[0] || userStore.userInfo?.username?.[0] }}
              </el-avatar>
              <span class="username">{{ userStore.userInfo?.nickname || userStore.userInfo?.username }}</span>
              <el-icon><arrow-down /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'USER'" command="profile">
                  <el-icon><user /></el-icon>个人资料
                </el-dropdown-item>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'USER'" command="friends">
                  <el-icon><user-filled /></el-icon>关注列表
                </el-dropdown-item>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'ADMIN'" command="dashboard">
                  <el-icon><Odometer /></el-icon>仪表盘
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><switch-button /></el-icon>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </header>

    <main class="main-content">
      <div class="content-wrapper">
        <el-card class="profile-card">
          <template #header>
            <h2 class="card-title">个人资料</h2>
          </template>
          <el-form
            ref="profileForm"
            :model="profileData"
            :rules="rules"
            label-width="100px"
            @submit.prevent="handleUpdateProfile"
          >
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="uploadHeaders"
              >
                <img v-if="profileData.avatar" :src="profileData.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>

            <el-form-item label="用户名">
              <el-input v-model="profileData.username" disabled />
            </el-form-item>

            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="profileData.nickname" />
            </el-form-item>

            <el-form-item label="旧密码" prop="oldPassword">
              <el-input
                v-model="profileData.oldPassword"
                type="password"
                show-password
                placeholder="不修改请留空"
              />
            </el-form-item>

            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="profileData.newPassword"
                type="password"
                show-password
                placeholder="不修改请留空"
              />
            </el-form-item>

            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input
                v-model="profileData.confirmPassword"
                type="password"
                show-password
                placeholder="不修改请留空"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" native-type="submit" :loading="updating">
                保存修改
              </el-button>
              <el-button @click="$router.push('/')">返回首页</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import {
  ArrowDown,
  User,
  UserFilled,
  SwitchButton,
  Plus,
  Odometer
} from '@element-plus/icons-vue'
import { getUserInfo, updateUserInfo } from '../api'

const router = useRouter()
const userStore = useUserStore()
const profileForm = ref(null)
const profileData = ref({
  username: '',
  nickname: '',
  avatar: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const updating = ref(false)

const fetchProfile = async () => {
  try {
    const response = await getUserInfo()
    const { password, ...userInfo } = response.data
    Object.assign(profileData.value, userInfo)
    await nextTick()
    if (profileForm.value) {
      profileForm.value.clearValidate()
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

onMounted(() => {
  fetchProfile()
})

const validatePass = (rule, value, callback) => {
  if (profileData.value.newPassword && !value) {
    callback(new Error('修改密码时必须输入旧密码'))
  } else {
    callback()
  }
}

const validateNewPass = (rule, value, callback) => {
  if (value && !profileData.value.oldPassword) {
    callback(new Error('请先输入旧密码'))
  } else {
    if (profileData.value.confirmPassword !== '') {
      profileForm.value?.validateField('confirmPassword')
    }
    callback()
  }
}

const validateConfirmPass = (rule, value, callback) => {
  if (profileData.value.newPassword && !value) {
    callback(new Error('请确认新密码'))
  } else if (value !== profileData.value.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  oldPassword: [
    { validator: validatePass, trigger: 'blur' }
  ],
  newPassword: [
    { validator: validateNewPass, trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPass, trigger: 'blur' }
  ]
}

const handleUpdateProfile = async () => {
  if (!profileForm.value) return

  try {
    await profileForm.value.validate()
    updating.value = true

    const updateData = {
      nickname: profileData.value.nickname,
      avatar: profileData.value.avatar
    }

    // 如果输入了新密码，则添加密码相关字段
    if (profileData.value.newPassword) {
      updateData.oldPassword = profileData.value.oldPassword
      updateData.password = profileData.value.newPassword
    }

    await updateUserInfo(updateData)
    ElMessage.success('更新成功')
    await userStore.fetchUserInfo()
    
    // 清空密码字段
    profileData.value.oldPassword = ''
    profileData.value.newPassword = ''
    profileData.value.confirmPassword = ''
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('更新失败，请稍后重试')
    }
  } finally {
    updating.value = false
  }
}

const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('token')}`
}

const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    profileData.value.avatar = response.data.url
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }

  return isImage && isLt2M
}

const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'friends':
      router.push('/friends')
      break
    case 'dashboard':
      router.push('/admin/dashboard')
      break
    case 'k-anonymity':
      router.push('/admin/k-anonymity')
      break
    case 'logout':
      userStore.logout()
      router.push('/login')
      break
  }
}

</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  height: 100%;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  text-decoration: none;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  color: var(--primary-color);
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  height: 200px;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-dropdown:hover {
  background-color: var(--background-color);
}

.username {
  margin: 0 8px;
  color: var(--text-color);
}

.main-content {
  padding-top: 80px;
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.profile-card {
  margin-bottom: 20px;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 5px;
}

@media screen and (max-width: 768px) {
  .content-wrapper {
    padding: 0 10px;
  }
}
</style> 